package vg.modules.minimap;

import java.awt.GridLayout;
import java.util.Observable;

import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

import vg.services.graph_view_manager.interfaces.graph_view.AGraphView;
import vg.services.graph_view_manager.interfaces.tab.ATab;
import vg.services.plugin_manager.event_and_request.event.AUIEvent;
import vg.services.plugin_manager.event_and_request.event.UIEventChangeTab;
import vg.services.user_interface_manager.interfaces.AUserInterfaceElement;

public class MiniMapPanel extends AUserInterfaceElement {
	// Swing components
	private final JPanel panel;
	private JComponent miniMapView = null;
	
	// Mutex
	private final Object theMutexObject = new Object();
	
	/**
	 * Constructor
	 */
	public MiniMapPanel() {
		super("Minimap", null);		
		this.panel = new JPanel(new GridLayout(1,1));
		this.panel.setSize(300, 300);
	}

	public JComponent getView() {
		return (this.panel);
	}

	public void update(Observable o, Object arg) {
		if (arg instanceof AUIEvent) {
			AUIEvent event = (AUIEvent) arg;
			switch (event.getType()) {
				case DEF_CHANGE_TAB: {
					final UIEventChangeTab bufEvent = (UIEventChangeTab) event;
					final ATab tab = bufEvent.getTab();
					if(SwingUtilities.isEventDispatchThread()) {
						synchronized (theMutexObject) {
							updateView(tab);
						}
					} else {
						SwingUtilities.invokeLater(new Runnable() {
							public void run() {
								synchronized (theMutexObject) {
									updateView(tab);
								}
							}
						});						
					}
					break;
				}
				
				case DEF_CHANGE_UI_STYLE: {
					if(SwingUtilities.isEventDispatchThread()) {
						synchronized (theMutexObject) {
							SwingUtilities.updateComponentTreeUI(panel);
						}						
					} else {
						SwingUtilities.invokeLater(new Runnable() {
							public void run() {
								synchronized (theMutexObject) {
									SwingUtilities.updateComponentTreeUI(panel);
								}
							}
						});												
					}
					break;
				}
				
				default:break;
			}
		}
	}
	
//=============================================================================
//-----------------PRIVATE METHODS---------------------------------------------
	private void updateView(ATab tab) {
		// delete old minimap
		if (miniMapView != null) {
			panel.remove(miniMapView);
		}
		// if new minimap != null -> setup it
		if (tab != null && tab.getTabType() == ATab.DEF_GRAPH_VIEW_TAB_TYPE) {
			miniMapView = ((AGraphView)tab).getGraphInformation().getMiniMap();
			if (miniMapView != null) {
				panel.add(miniMapView);
			}
		}
		panel.updateUI();		
	}
}
